package org.android.pasos.util;

import static java.math.RoundingMode.CEILING;
import static java.text.DateFormat.SHORT;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;

import org.android.pasos.Constants;
import org.android.pasos.DatosTrama;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class UtilTrama {

	private static DatosTrama datostrama;
	private static DateFormat dateFormat = java.text.DateFormat
			.getDateInstance(SHORT, Locale.ENGLISH);
	private static LocationManager locationManager;
	private static Criteria criteria;

	public static DatosTrama creartrama(Context ctx) {
		datostrama = new DatosTrama();
		batteryLevel(ctx);
		SharedPreferences mPrefs = ctx.getSharedPreferences("PasosPreferences", 0);
		if (!mPrefs.getString("Papellido1", "vacio").equals("Emu")) {
			TelephonyManager tm = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId(); // getDeviceId() Obtiene el imei
			Context context = ctx.getApplicationContext();
			locationManager = (LocationManager) ctx.getApplicationContext()
					.getSystemService(Context.LOCATION_SERVICE);
			criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_COARSE);

			locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			String provider = locationManager.NETWORK_PROVIDER;
			Location location = locationManager
					.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
			// printLocationByType(location, provider, "Last");
			locationManager.requestLocationUpdates(provider, 600, 20,
					singeUpdateListener, context.getMainLooper());
			datostrama.setAlarma("11");

			long time = location.getTime();
			dateFormat.format(new Date(time));
			Calendar cal = dateFormat.getCalendar();
			String fecha = getFecha(cal);
			String hora = getHora(cal);

			datostrama.setLd(fecha);
			datostrama.setLh(hora);			
			
			BigDecimal longitud = new BigDecimal(location.getLongitude())
					.setScale(4, CEILING);
			datostrama.setLn(longitud);
			BigDecimal latitud = new BigDecimal(location.getLatitude())
					.setScale(4, CEILING);
			datostrama.setLt(latitud);
			BigDecimal altura = new BigDecimal(location.getAltitude());
			Log.d(Constants.LOGTAG, "Altura: " + altura);
			if (altura.intValue() != 0)
				datostrama.setLa(altura);
			datostrama.setRd(imei);
		}		
		datostrama.datosTrama();
		return datostrama;
	}

	private static LocationListener singeUpdateListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			Log.d(Constants.LOGTAG, "Single Location Update Received: "
					+ location.getLatitude() + "," + location.getLongitude()
					+ "," + location.getAltitude());
			// printLocationByType(location, location.getProvider(), "Actual");

			long time = location.getTime();
			dateFormat.format(new Date(time));
			Calendar cal = dateFormat.getCalendar();
			String fecha = getFecha(cal);
			String hora = getHora(cal);

			datostrama.setLd(fecha);
			datostrama.setLh(hora);

			BigDecimal longitud = new BigDecimal(location.getLongitude())
					.setScale(4, CEILING);
			datostrama.setLn(longitud);
			BigDecimal latitud = new BigDecimal(location.getLatitude())
					.setScale(4, CEILING);
			datostrama.setLt(latitud);
			BigDecimal altura = new BigDecimal(location.getAltitude());
			if (altura.intValue() != 0)
				datostrama.setLa(altura);
			datostrama.datosTrama();

			locationManager.removeUpdates(singeUpdateListener);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
		}
	};

	private static String getFecha(Calendar c) {
		String annio, mes, dia;

		annio = Integer.toString(c.get(Calendar.YEAR));
		mes = Integer.toString(c.get(Calendar.MONTH) + 1);
		if (c.get(Calendar.MONTH) + 1 < 10) {
			mes = "0" + mes;
		}
		dia = Integer.toString(c.get(Calendar.DATE));
		if (c.get(Calendar.DATE) < 10) {
			dia = "0" + dia;
		}

		return annio + mes + dia;
	}

	private static String getHora(Calendar c) {
		String hora, min, seg;

		hora = Integer.toString(c.get(Calendar.HOUR_OF_DAY));
		if (c.get(Calendar.HOUR_OF_DAY) < 10) {
			hora = "0" + hora;
		}

		min = Integer.toString(c.get(Calendar.MINUTE));
		if (c.get(Calendar.MINUTE) < 10) {
			min = "0" + min;
		}

		seg = Integer.toString(c.get(Calendar.SECOND));
		if (c.get(Calendar.SECOND) < 10) {
			seg = "0" + seg;
		}
		return hora + min + seg;
	}

	private static void batteryLevel(Context ctx) {
		BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				context.unregisterReceiver(this);
				int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,
						-1);
				int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
				int level = -1;
				if (rawlevel >= 0 && scale > 0) {
					level = (rawlevel * 100) / scale;
				}
				Log.d(Constants.LOGTAG, "PB: " + level);
				datostrama.setPb(level);
			}
		};
		IntentFilter batteryLevelFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		ctx.registerReceiver(batteryLevelReceiver, batteryLevelFilter);
	}
}
